package com.flyou.ccnucenter.ui.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.e1858.myalertview.AlertView;
import com.e1858.myalertview.OnItemClickListener;
import com.flyou.ccnucenter.Constant;
import com.flyou.ccnucenter.R;
import com.flyou.ccnucenter.utils.OkHttpClientManager;
import com.flyou.ccnucenter.utils.OpenFileUtils;
import com.flyou.ccnucenter.utils.SDCardUtils;
import com.flyou.ccnucenter.utils.SPUtils;
import com.flyou.ccnucenter.utils.UrlUtils.departments.ComputerNewsitemShow;
import com.flyou.ccnucenter.utils.UrlUtils.departments.FaNewsitemShow;
import com.flyou.ccnucenter.utils.UrlUtils.departments.HuaXueNewsitemShow;
import com.flyou.ccnucenter.utils.UrlUtils.departments.GuoJiNewsitemShow;
import com.flyou.ccnucenter.utils.UrlUtils.departments.HuanJingNewsitemShow;
import com.flyou.ccnucenter.utils.UrlUtils.departments.JYXXNewsitemShow;
import com.flyou.ccnucenter.utils.UrlUtils.departments.JkyNewsitemShow;
import com.flyou.ccnucenter.utils.UrlUtils.departments.LiShiNewsitemShow;
import com.flyou.ccnucenter.utils.UrlUtils.departments.LifeNewsitemShow;
import com.flyou.ccnucenter.utils.UrlUtils.departments.MaKeSiNewsitemShow;
import com.flyou.ccnucenter.utils.UrlUtils.departments.MinSHengNewsitemShow;
import com.flyou.ccnucenter.utils.UrlUtils.departments.MusicNewsitemShow;
import com.flyou.ccnucenter.utils.UrlUtils.departments.ShangNewsitemShow;
import com.flyou.ccnucenter.utils.UrlUtils.departments.SheHuiNewsitemShow;
import com.flyou.ccnucenter.utils.UrlUtils.departments.ShuXueNewsitemShow;
import com.flyou.ccnucenter.utils.UrlUtils.departments.WaiYuNewsitemShow;
import com.flyou.ccnucenter.utils.UrlUtils.departments.WenXueNewsitemShow;
import com.flyou.ccnucenter.utils.UrlUtils.departments.XinLiNewsitemShow;
import com.flyou.ccnucenter.utils.UrlUtils.departments.XinWenNewsitemShow;
import com.flyou.ccnucenter.utils.UrlUtils.departments.XinXiNewsitemShow;
import com.flyou.ccnucenter.utils.UrlUtils.departments.YaoNewsitemShow;
import com.flyou.ccnucenter.utils.UrlUtils.departments.YiNewsitemShow;
import com.flyou.ccnucenter.utils.UrlUtils.departments.ZheXueNewsitemShow;
import com.flyou.ccnucenter.utils.UrlUtils.departments.ZhengZhiNewsitemShow;
import com.flyou.ccnucenter.utils.UrlUtils.main.NewsItemPaster;
import com.flyou.ccnucenter.utils.UrlUtils.message.ActivityMessagePaster;
import com.flyou.ccnucenter.utils.UrlUtils.message.NotfitcationMessagePaster;
import com.flyou.ccnucenter.widget.FousedTextView;
import com.flyou.ccnucenter.widget.loading.LoadingView;
import com.squareup.okhttp.Request;

import java.io.File;

public class NewsDetialActivity extends BaseActivity1 implements View.OnClickListener {
    private String mNewsUrl;
    private WebView webView;
    private RelativeLayout mTitlebarRlBack;
    private FousedTextView mTitlebarTvTitle;
    private RelativeLayout mTitlebarRlSearch;
    private LoadingView mLoadView;
    private RelativeLayout failed_view;
    private Button reTry;
    private String fromClassName;
    private AlertView mAlertView;
    private String mNewsTitle;
    private RelativeLayout correntlayout;

    @Override
    protected void initView() {
        setContentView(R.layout.activity_news_detial);
        correntlayout = (RelativeLayout) findViewById(R.id.correntlayout);
        mTitlebarRlSearch = (RelativeLayout) findViewById(R.id.titlebar_rl_Right);
        mTitlebarRlBack = (RelativeLayout) findViewById(R.id.titlebar_rl_back);
        mTitlebarTvTitle = (FousedTextView) findViewById(R.id.titlebar_tv_title);

        failed_view = (RelativeLayout) findViewById(R.id.failed_view);
        reTry = (Button) findViewById(R.id.reTry);
        mLoadView = (LoadingView) findViewById(R.id.loadingView);
        mLoadView.setLoadingText("正在拼命加载数……");

        webView = (WebView) findViewById(R.id.newsWebView);
        mTitlebarRlSearch.setVisibility(View.VISIBLE);

    }

    @Override
    protected void initDate() {
        //        获取传来的参数
        Intent intent = getIntent();
        mNewsTitle = intent.getStringExtra(Constant.SCHOOL_NEWS_TITLE);
        mNewsUrl = intent.getStringExtra(Constant.SCHOOL_NEWS_URL);

        fromClassName = intent.getStringExtra(Constant.DEPARTMENT_NAME);


//        设置UI显示
        mTitlebarTvTitle.setTextSize(15);
        mTitlebarTvTitle.setText(mNewsTitle);

        //        设置webView
        mLoadView.setVisibility(View.VISIBLE);
        webView.setBackgroundColor(0);
        WebSettings webSettings = webView.getSettings();
        webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        String ua = webView.getSettings().getUserAgentString();
        webView.getSettings().setUserAgentString(ua.replace("Android", "UCWEB/2.0(Linux;U;Adr 2.3;zh-CN;MI-ONEPlus)U2/1.0.0UCBrowser/8.6.0.199U2/1.0.0Mobile "));

        webSettings.setJavaScriptEnabled(true);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setBlockNetworkImage(false);
        webSettings.setDefaultTextEncodingName("utf-8");
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setTextSize(WebSettings.TextSize.NORMAL);
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageFinished(WebView view, String url) {
                mLoadView.setVisibility(View.GONE);
                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(NewsDetialActivity.this, "加载失败", Toast.LENGTH_SHORT).show();
                super.onReceivedError(view, errorCode, description, failingUrl);
            }
        });
        webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);

        String itemNews = (String) SPUtils.get(NewsDetialActivity.this, mNewsUrl, "");
        if (!TextUtils.isEmpty(itemNews)) {

            failed_view.setVisibility(View.GONE);
            mLoadView.setVisibility(View.VISIBLE);


            webView.loadDataWithBaseURL(mNewsUrl, itemNews, "text/html", "utf-8", null);
            webView.setDownloadListener(new MyWebViewDownLoadListener());

        }
//        执行网络加载操作
        else {
            new GetNewsHtmlBody().execute(mNewsUrl);
        }


    }

    @Override
    protected void setListener() {
        mTitlebarRlBack.setOnClickListener(this);
        reTry.setOnClickListener(this);
        mTitlebarRlSearch.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.titlebar_rl_back:
                if (webView.canGoBack()) {
                    webView.goBack();
                } else {
                    finish();
                }
                break;

            case R.id.titlebar_rl_Right:

                break;
            case R.id.reTry:
                new GetNewsHtmlBody().execute(mNewsUrl);
                failed_view.setVisibility(View.GONE);

                mLoadView.setVisibility(View.VISIBLE);
                break;
        }
    }

    class GetNewsHtmlBody extends AsyncTask<String, String, String> {
        @Override
        protected String doInBackground(String... params) {
            String newsbodyHtml = "";
            switch (fromClassName) {
                case "SchoolNewFragment":
                    newsbodyHtml = new NewsItemPaster().getNewsbody(params[0]);
                    break;
                case "JiaoKeYuanFragment":
                    newsbodyHtml = JkyNewsitemShow.getNewsbody(params[0]);
                    break;
                case "MinShengFragment":
                    newsbodyHtml = MinSHengNewsitemShow.getNewsbody(params[0]);
                    break;
                case "HuaXueFragment":
                    newsbodyHtml = HuaXueNewsitemShow.getNewsbody(params[0]);
                    break;
                case "WenXueFragment":
                    newsbodyHtml = WenXueNewsitemShow.getNewsbody(params[0]);
                    break;
                case "YaoXueFragment":
                    newsbodyHtml = YaoNewsitemShow.getNewsbody(params[0]);
                    break;

                case "YiXueFragment":
                    newsbodyHtml = YiNewsitemShow.getNewsbody(params[0]);
                    break;
                case "HuanJingFragment":
                    newsbodyHtml = HuanJingNewsitemShow.getNewsbody(params[0]);
                    break;
                case "JiSuanJiFragment":
                    newsbodyHtml = ComputerNewsitemShow.getNewsbody(params[0]);
                    break;
                case "ShengMingFragment":
                    newsbodyHtml = LifeNewsitemShow.getNewsbody(params[0]);
                    break;
                case "ZheXueFragment":
                    newsbodyHtml = ZheXueNewsitemShow.getNewsbody(params[0]);
                    break;
                case "LiShiFragment":
                    newsbodyHtml = LiShiNewsitemShow.getNewsbody(params[0]);
                    break;
                case "XinWenFragment":
                    newsbodyHtml = XinWenNewsitemShow.getNewsbody(params[0]);
                    break;
                case "ShangFragment":
                    newsbodyHtml = ShangNewsitemShow.getNewsbody(params[0]);
                    break;

                case "NotficationMessageFragment":
                    newsbodyHtml = new NotfitcationMessagePaster().getNewsbody(params[0]);
                    break;
                case "ActivityMessageFragment":
                    newsbodyHtml = new ActivityMessagePaster().getNewsbody(params[0]);
                    break;
                case "PersonalMessageFragment":
                    newsbodyHtml = new ActivityMessagePaster().getNewsbody(params[0]);
                    break;
                case "WuLiFragment":
                    newsbodyHtml = new WaiYuNewsitemShow().getNewsbody(params[0]);
                    break;
                case "MaKeSiFragment":
                    newsbodyHtml = new MaKeSiNewsitemShow().getNewsbody(params[0]);
                    break;

                case "ZhengZhiFragment":
                    newsbodyHtml = new ZhengZhiNewsitemShow().getNewsbody(params[0]);
                    break;
                case "SheHuiFragment":
                    newsbodyHtml = new SheHuiNewsitemShow().getNewsbody(params[0]);
                    break;
                case "XinLiFragment":
                    newsbodyHtml = new XinLiNewsitemShow().getNewsbody(params[0]);
                    break;
                case "ShuXueFragment":
                    newsbodyHtml = new ShuXueNewsitemShow().getNewsbody(params[0]);
                    break;
                case "GuoJiFragment":
                    newsbodyHtml = new GuoJiNewsitemShow().getNewsbody(params[0]);
                    break;  case "XinXiFragment":
                    newsbodyHtml = new XinXiNewsitemShow().getNewsbody(params[0]);
                    break; case "MusicFragment":
                    newsbodyHtml = new MusicNewsitemShow().getNewsbody(params[0]);
                    break;case "FaFragment":
                    newsbodyHtml = new FaNewsitemShow().getNewsbody(params[0]);
                    break;case "JYXXFragment":
                    newsbodyHtml = new JYXXNewsitemShow().getNewsbody(params[0]);
                    break;

            }


            return newsbodyHtml;
        }

        @Override
        protected void onPostExecute(String s) {

//使用基本地址加载url 参数： 请求的地址（可以为网站的root地址、要加载的html片段、显示的格式、编码、错误页面）

            if (TextUtils.isEmpty(s)) {
                failed_view.setVisibility(View.VISIBLE);

                mLoadView.setVisibility(View.GONE);
            } else {
                failed_view.setVisibility(View.GONE);
                mLoadView.setVisibility(View.VISIBLE);
//                将html片段缓存到本地
                SPUtils.put(NewsDetialActivity.this, mNewsUrl, s);
                webView.loadDataWithBaseURL(mNewsUrl, s, "text/html", "utf-8", null);
            }
            super.onPostExecute(s);
        }
    }

    private class MyWebViewDownLoadListener implements DownloadListener {

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                                    long contentLength) {
            if (!SDCardUtils.isSDCardEnable()) {
                Toast.makeText(NewsDetialActivity.this, "sd卡不可用", Toast.LENGTH_SHORT).show();
                return;
            }
            File file = new File(SDCardUtils.getSDCardPath() + File.separator + "henu_doc");
            if (!file.exists()) {
                file.mkdirs();
            }
            Toast.makeText(NewsDetialActivity.this, "正在下载文件，请稍后……", Toast.LENGTH_SHORT).show();
            OkHttpClientManager.getDownloadDelegate().downloadAsyn(url, file.getPath(), new OkHttpClientManager.ResultCallback<String>() {
                @Override

                public void onError(Request request, Exception e) {
                    Toast.makeText(NewsDetialActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onResponse(final String response) {

                    mAlertView = new AlertView("打开文件", "文件已经下载完成，是否现在打开？", "稍后再说", null, new String[]{"现在就看"}, NewsDetialActivity.this, AlertView.Style.Alert, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int position) {

                            switch (position) {

                                case 0:
                                    //                    打开文件
                                    Intent intent = OpenFileUtils.openFile(response);
                                    startActivity(intent);
                                    break;
                            }
                        }
                    });
                    mAlertView.show();
                }

                @Override
                public void onBefore(Request request) {
                    super.onBefore(request);


                }


            });
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (webView.canGoBack()) {
                webView.goBack();
            } else {
                finish();
            }
            if (mAlertView != null && mAlertView.isShowing()) {
                mAlertView.dismiss();
                return false;
            }
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        webView.destroy();
    }

}
